<script setup lang="ts">
import { onMounted, watch, ref, unref, onUnmounted, markRaw } from "vue";
import { ElMessage } from "element-plus";
import { Edit, Document, Refresh, Setting } from "@element-plus/icons-vue";
import Login from "../Login/Index.vue";
import AddModel from "./AddModel.vue";
import UserConfig from "./UserConfig.vue";
import { debounce } from "lodash";
import * as echarts from "echarts";
import {
  GetModelName,
  GetLineInfo,
  SaveLineInfo,
  LineControl,
  GetLineState,
} from "../../api";

const styleTotal = ref(3 * 10);

const currentStyle = ref(1);
const handleStyleChange = (current: number) => {
  currentStyle.value = current;
  connectRun.value && setDeviceStatus();
};
//设备个数
const deviceNum = ref(61);
const finalNum = ref(61);

//第一版
const rowList1 = ref<any[]>([]);
const rowList2 = ref<any[]>([]);
const specialList1 = ref([
  { UseStatus: "1", Status: 6, Number: "T1" },
  { UseStatus: "1", Status: 6, Number: "T2" },
]);
//第二版
const rowList12 = ref<any[]>([]);
const rowList22 = ref<any[]>([]);
const specialList2 = ref<any[]>([]);
//第三版
const rowList13 = ref<any[]>([]);
//初始化style1 2 3
const initDeviceMode = () => {
  rowList1.value = Array.from({ length: finalNum.value }, (item, index) => {
    return {
      UseStatus: "1",
      Status: "6",
      Number: index + 1,
    };
  });
  rowList2.value = Array.from(
    { length: 120 - finalNum.value },
    (item, index) => {
      return {
        UseStatus: "1",
        Status: "6",
        Number: index + (finalNum.value + 1),
      };
    }
  );
  rowList12.value = Array.from({ length: finalNum.value }, (item, index) => {
    return {
      UseStatus: "1",
      Status: "6",
      Number: index + 1,
    };
  });
  rowList22.value = Array.from(
    { length: 120 - finalNum.value - 1 },
    (item, index) => {
      return {
        UseStatus: "1",
        Status: "6",
        Number: index + (finalNum.value + 2),
      };
    }
  );
  specialList2.value = [
    { UseStatus: "1", Status: 6, Number: "T1" },
    { UseStatus: "1", Status: 6, Number: finalNum.value + 1 },
    { UseStatus: "1", Status: 6, Number: "T2" },
  ];
  rowList13.value = Array.from({ length: finalNum.value }, (item, index) => {
    return {
      UseStatus: "1",
      Status: "6",
      Number: index + 1,
    };
  });
};
const model = ref("");
const modelList = ref<any[]>([]);
const getModelList = () => {
  GetModelName().then((res: any) => {
    if (res.code === 200) {
      modelList.value = res.data;
      //获取线体信息
      getList();
    }
  });
};
const lineList = ref<any[]>([]);
const getList = () => {
  return new Promise((resolve: any, reject: any) => {
    GetLineInfo({
      line: model.value ? model.value : "0",
    }).then((res: any) => {
      if (res.code == 200) {
        const { FLineEntity } = JSON.parse(JSON.stringify(res.data));
        lineList.value = FLineEntity.map((item: any, index: number) => {
          return {
            ...item,
            Index: index + 1,
            Activity: JSON.parse(item.Activity),
            Status: JSON.parse(item.Status),
          };
        });
      }
    });
  });
};

const stateList = ref<any[]>(Array.from({ length: 10 }, (item) => "1"));
//获取设备状态
const basicList = ref([]);
const formatDeviceList = () => {
  const temp = JSON.parse(JSON.stringify(unref(basicList)));
  // debugger
  const firstRow = temp.slice(0, finalNum.value);
  //style1 62在下面情况；style2 62在中间情况 将接口数据索引为61的数据赋值给firstRow
  const startLength =
    currentStyle.value === 1 ? finalNum.value : finalNum.value + 1;
  const secondRow = temp.slice(startLength, temp.length + 1);
  // console.log(`output->firstRow,secondRow`, firstRow, secondRow);
  let temp1 = firstRow.map((item: any, index: number) => {
    return {
      ...item,
      Number: index + 1,
    };
  });
  const tempLength =
    currentStyle.value === 1 ? finalNum.value + 1 : finalNum.value + 2;
  const temp2 = secondRow.map((item: any, index: number) => {
    return {
      ...item,
      Number: index + tempLength,
    };
  });

  //如果是样式1 取索引为61 编码62赋值为rowList2; 样式2 取索引为61为rowList22
  if (currentStyle.value === 1) {
    // T1跟着61（deviceNum.value) status T2跟着62Status
    specialList1.value[0].Status = temp1[temp1.length - 1].Status;
    specialList1.value[1].Status = temp2[0].Status;
  } else if (currentStyle.value === 2) {
    // T1跟着61status 62取62 T2跟着62Status
    specialList2.value[0].Status = temp1[temp1.length - 1].Status;
    specialList2.value[1].Number = finalNum.value + 1;
    specialList2.value[1].Status = temp[finalNum.value].Status;
    specialList2.value[2].Status = temp[finalNum.value].Status;
  } else {
    const temp = JSON.parse(JSON.stringify(unref(basicList)));
    temp1 = temp.map((item: any, index: number) => {
      return {
        ...item,
        Number: index + 1,
      };
    });
    // console.log(`66666666output->temp1`, temp1);
  }
  const result = { temp1, temp2 };
  return result;
};
//设置设备状态
const setDeviceStatus = () => {
  const { temp1, temp2 } = formatDeviceList();

  if (currentStyle.value === 1) {
    rowList1.value = temp1;
    rowList2.value = temp2;
  } else if (currentStyle.value === 2) {
    rowList12.value = temp1;
    rowList22.value = temp2;
  } else {
    rowList13.value = temp1;
    // console.log(`output->rowList13`,rowList13)
  }
};
//保存设备个数
const saveDeviceNum = () => {
  finalNum.value = deviceNum.value;
  localStorage.setItem("DEVICE_NUM", JSON.stringify(unref(finalNum)));
  if (linkRun.value) {
    setDeviceStatus();
  } else {
    initDeviceMode();
  }
};
//获取日志信息
const logList = ref([]);
//获取异常设备信息
const errorList = ref<any[]>([]);

//刷新周期
const cycle = ref(5000);

//控制linkRun开关是否启用 默认可编辑false 不能编辑true
const runActive = ref(false);
//联动运行-开启时列表中的
const linkRun = ref(false);
const connectRun = ref(false);

//只改变列表状态
const changeRun = () => {
  if (linkRun.value) {
    emit("updateStatus", "running");
  } else {
    emit("updateStatus", "pending");
  }
  //开启(定时执行请求接口)
  //开启时自动开启运行开关，关闭时自动关闭
  lineList.value = lineList.value.map((item: any) => {
    return {
      ...item,
      Status: linkRun.value ? (item.Activity ? true : false) : false,
    };
  });
  // console.log(`output->lineList.value`, lineList.value);
  //状态变化 调用保存接口
  const post = {
    line: model.value ? model.value : "0",
    fLineEntity: lineList.value,
    powerState: linkRun.value,
    mode: mode.value,
  };
  SaveLineInfo(post).then((res: any) => {
    if (res.code !== 200) {
      ElMessage.error(res.msg);
    }
    ElMessage.success(res.msg);
  });
};

let connectIntervalID = ref();
//把之前linkRun里的接口逻辑放到这里 负责接口和定时器任务
const changeConnect = () => {
  lineFlag.value = false;
  clearAllTimer();
  //运行为True时 启动定时器
  if (connectRun.value) {
    //开启后台
    lineState();
    // 开启LineState轮询
    lineFlag.value = true;
    lineLoop();
    //每隔10分钟清除定时器
    setMyInterval(options);
  }
};

const changeLineStatus = (data: any, index: number) => {
  const { Activity, Status } = data;
  if (linkRun.value) {
    if (Activity) {
      //run
      saveLine(index);
    }
  } else {
    if (Activity) {
      if (!Status) {
        //stop
        saveLine(index);
      }
    }
  }
};

//线段信息 下一行开始大于上一行结束
const colChanged = (index: number, EndNum: string) => {
  console.log(index, EndNum);
  //只有当当前行不是最后一行时才做赋值
  if (checkNum(EndNum)) {
    if (index !== lineList.value.length || !EndNum) {
      //将当前行的值+1 赋值给下一行的开始
      lineList.value[index + 1].StartNum = Number(EndNum) + 1;
    }
  }
};
//开始编号需小于结束编号
const checkEndNum = (data: any, index: number) => {
  const { StartNum, EndNum } = data;
  if (checkNum(EndNum)) {
    if (StartNum > EndNum) {
      ElMessage.warning("结束编号不能小于开始编号");
      lineList.value[index].EndNum = StartNum;
      colChanged(index, StartNum);
      return;
    }
  }
};
const checkNum = (EndNum: string) => {
  const reg = /^[1-9]\d*$/;
  if (EndNum && !reg.test(EndNum)) {
    ElMessage.warning("结束编号仅支持数字格式");
    return false;
  }
  return true;
};

const loginRef = ref();
const isEdit = ref(false);
const edit = () => {
  //当前设备如果处于运行中 则不能编辑
  if (linkRun.value) {
    ElMessage.warning("当前设备运行中，不能进行编辑操作");
    return;
  }
  //调出登录窗口
  loginRef.value.open("edit");
  // isEdit.value = true;
};
const modelRef = ref();
const addModel = () => {
  modelRef.value.open();
};
const userRef = ref();
const configUser = () => {
  loginRef.value.open("config");
};

const closeLogin = (type: string) => {
  if (type === "edit") {
    isEdit.value = true;
  } else {
    userRef.value.open();
  }
};
const refreshModel = () => {
  GetModelName().then((res: any) => {
    if (res.code === 200) {
      modelList.value = res.data;
    }
  });
};
const emit = defineEmits([
  "updateStatus",
  "updateDevice",
  "updateLog",
  "updateFault",
  "updateAlarm",
  "updateSST",
]);
const saveLine = (index: number) => {
  const post = {
    line: model.value ? model.value : "0",
    fLineEntity: index === -1 ? lineList.value : [lineList.value[index]],
    powerState: linkRun.value,
    mode: mode.value,
  };
  return new Promise((resolve) => {
    SaveLineInfo(post).then((res: any) => {
      if (res.code !== 200) {
        ElMessage.error(res.msg);
        resolve(false);
      }
      ElMessage.success(res.msg);
      resolve(true);
    });
  });
};
const save = async () => {
  //model为空 不能保存
  if (!model.value) {
    ElMessage.warning("请选择机种");
    return;
  }
  //缓存当前的Model
  localStorage.setItem("CURRENT_MODEL", model.value);
  const res = await saveLine(-1);
  if (res) {
    isEdit.value = false;
    getList();
  }
};

const timerList = ref([]);
const clearAllTimer = () => {
  // 清除所有的定时器
  for (let i = 0; i < timerList.value.length; i++) {
    clearTimeout(timerList.value[i]);
  }
  // 清除列表
  timerList.value = [];
  console.log("clearAllTimerList", timerList.value);
};

const changeActivity = (activity: boolean, index: number) => {
  //启用关闭 运行跟着关闭
  if (!activity) {
    lineList.value[index].Status = activity;
  }
};

/**
 * line loop
 */
const lineLoopTimer = ref();
//异步请求拿到结果 停止轮询
const syncPromiseLine = () => {
  return new Promise((resolve) => {
    GetLineState({
      line: model.value ? model.value : "0",
    })
      .then((res: any) => {
        if (res.code == 200) {
          const {
            StateInfo,
            StatusInfo,
            SSTInfo,
            AbnormalInfo,
            AlarmInfo,
            FaultInfo,
            LogInfo,
          } = res.data;
          basicList.value = JSON.parse(JSON.stringify(StatusInfo));
          //列表状态一列信息
          stateList.value = StateInfo;
          //渲染设备状态
          setDeviceStatus();
          //异常设备
          errorList.value = AbnormalInfo;
          //日志信息
          logList.value = LogInfo;
          emit("updateLog", LogInfo);
          //设备状态
          emit("updateDevice", StatusInfo);
          //故障TOP
          emit("updateFault", FaultInfo);
          //急停TOP
          emit("updateAlarm", AlarmInfo);
          //状态统计
          sstData.value = JSON.parse(JSON.stringify(SSTInfo));
          emit("updateSST", SSTInfo);
          if (res.outputStr == "Y") {
            lineState();
          }
          resolve(1);
        }
      })
      .catch((err) => {
        resolve(1);
      });
  });
};
//控制轮询的间隔时间 并在指定时间执行请求
const pollingPrimiseLine = () => {
  return new Promise((resolve) => {
    lineLoopTimer.value = setTimeout(async () => {
      const result = await syncPromiseLine();
      resolve(result);
    }, cycle.value);
    timerList.value.push(lineLoopTimer.value);
  });
};
//轮询入口
const lineFlag = ref(true);
const startPollingLine = async () => {
  clearTimeout(lineLoopTimer.value);
  lineLoopTimer.value = "";
  let needPolling = await syncPromiseLine();
  console.log(
    `output->needPolling, lineFlag.value`,
    needPolling,
    lineFlag.value
  );
  while (needPolling && lineFlag.value) {
    needPolling = await pollingPrimiseLine();
  }
  console.log("设备状态轮询请求处理完成！");
};
const lineLoop = async () => {
  await startPollingLine();
  console.log("设备状态请求被clearTimeOut 这里不会被执行");
};

const lockMask = ref(false);
const toggleLock = () => {
  lockMask.value = !lockMask.value;
};

//限速变化 传参
const delay = ref(5 * 1000);
const changeVelocity = debounce((index) => {
  console.log(`output->index`, index);
  saveLine(index);
}, delay.value);
function lineState() {
  //将启用true传过去
  const data = lineList.value.filter((item) => item.Activity);
  const post = {
    line: model.value ? model.value : "0",
    fLineEntity: data,
    powerState: linkRun.value,
    mode: mode.value,
  };
  LineControl(post).then((res: any) => {
    if (res.code == 200) {
      console.log(`output->success`);
    }
  });
}
//requestAnimationFrame
const setMyInterval = (options: any) => {
  const requestAnimationFrame =
    window.requestAnimationFrame || window.webkitRequestAnimationFrame;
  let i = 1;
  let count = 1;
  options.timer = options.timer || null;
  const loop = () => {
    options.timer = requestAnimationFrame(loop);
    if (i % 60 === 0) {
      // 此处 60 代表屏幕刷新率为60HZ，即代表此处每隔一秒执行一次
      const timeout = options.timeout || 1000;
      if (count % parseInt((timeout / 1000).toString()) === 0) {
        // 每隔多少秒调用一次回调函数，此处timeout应为1000的倍数
        options.callback && options.callback();
      }
      count++;
    }
    i++;
  };
  options.timer = requestAnimationFrame(loop);
};
let options = {
  timer: null,
  callback: () => {},
  timeout: 1000,
};

const tenMinutes = 10 * 60 * 1000;
options.timeout = tenMinutes;
let tempTimer = ref();
options.callback = () => {
  //当开启的状态每隔10分钟清除
  if (connectRun.value) {
    // 当前lineFlag为true且lineLoopTimer true 清除GetLineState定时器
    if (lineFlag.value && lineLoopTimer.value) {
      clearTimeout(lineLoopTimer.value);
      lineLoopTimer.value = "";
      clearAllTimer();
      lineFlag.value = false;
      tempTimer.value = setTimeout(() => {
        lineFlag.value = true;
        lineLoop();
        clearTimeout(tempTimer.value);
        tempTimer.value = "";
        console.log(`output->clear success`);
      }, 0);
      console.log("clearLineLoopTimer", lineLoopTimer.value);
    }
  }
};

//设备状态统计
//获取chart实例
const chart = ref();
//获取echarts
let myChart = ref();
const sstData = ref<any[]>();

const colorList = ["#fff", "#e6a23c", "#cece1d", "#f56c6c", "#67c23a"];
const legendList = ["离线", "急停", "待机", "故障", "运行"];
const chartOptions = ref({
  title: {
    text: "单位：台",
    right: 15,
    bottom: 10,
    textStyle: {
      color: "#799ac1",
    },
  },
  tooltip: {
    trigger: "item",
    formatter: "{b} : {c} ({d}%)",
  },
  legend: {
    width: 360,
    top: 25,
    left: 50,
    itemGap: 30,
    itemWidth: 20,
    itemHeight: 20,
    textStyle: {
      fontSize: 22,
      color: "#799ac1",
      // 文字块背景色，一定要加上，否则对齐不会生效
      backgroundColor: "transparent",
      rich: {
        b: {
          width: 60,
          fontSize: 22,
        },
      },
    },
    formatter: (name: any) => {
      const series = myChart.value.getOption().series[0];
      const temp = series.data.filter((row: any) => row.name === name);
      const val = (temp.length && temp[0].value) || 0;
      return `${name} {b|${val}}`;
    },
  },
  series: [
    {
      type: "pie",
      top: 150,
      avoidLabelOverlap: false,
      radius: ["40%", "75%"],
      center: ["50%", "50%"],
      data: legendList.map((item, index) => {
        return {
          name: legendList[index],
          value: 0,
          itemStyle: { color: colorList[index] },
        };
      }),
      label: {
        show: false,
        color: "#799ac1",
        fontSize: 20,
        formatter: "{c}台",
      },
      labelLine: {
        length: 5,
        length2: 3,
      },
    },
  ],
});
//状态统计
watch(
  () => sstData,
  (newVal: any, oldVal) => {
    // console.log('new', newVal)
    const result = newVal.value;
    chartOptions.value.series[0].data[0].value = result[0].value;
    chartOptions.value.series[0].data[1].value = result[4].value;
    chartOptions.value.series[0].data[2].value = result[1].value;
    chartOptions.value.series[0].data[3].value = result[3].value;
    chartOptions.value.series[0].data[4].value = result[2].value;
    myChart.value.setOption(chartOptions.value);
  },
  {
    deep: true,
  }
);

//使用eventBus声明开启接口的方法，便于设备控制调用
// eventBus.on('runApi', runApi)

//顺序执行 1线体信息 2连接设备状态
onMounted(() => {
  const currentModel = localStorage.getItem("CURRENT_MODEL");
  model.value = currentModel || "";
  const storageDeviceNum = localStorage.getItem("DEVICE_NUM");
  const tempNum = storageDeviceNum ? Number(storageDeviceNum) : deviceNum.value;
  deviceNum.value = tempNum;
  finalNum.value = tempNum;
  initDeviceMode();
  getModelList();
  initChart();
});
window.addEventListener("resize", () => {
  myChart.value?.resize();
});

const initChart = () => {
  myChart.value = markRaw(
    echarts.init(chart.value, "white", { width: "350px", height: "540px" })
  );
  myChart.value.setOption(chartOptions.value);
};

//卸载时销毁实例
onUnmounted(() => {
  clearAllTimer();
  window.removeEventListener("resize", myChart.value);
  // 卸载echarts实例
  myChart.value.dispose();
  //清除定时器
  clearInterval(connectIntervalID.value);
});

const mode = ref("Normal");
</script>

<template>
  <div class="my-box device-status">
    <div class="flex items-center justify-between">
      <div class="flex items-center">
        <div class="my-box-title">设备状态</div>
        <div class="flex items-center ml-10">
          <div class="flex gap-2 btn-box">
            <el-button>离线</el-button>
            <el-button class="my-btn">待机</el-button>
            <el-button type="success">运行</el-button>
            <el-button type="warning">急停</el-button>
            <el-button type="danger">故障</el-button>
          </div>
        </div>
      </div>
      <!-- 设备状态 -->
      <div class="flex content-center items-center justify-between">
        <div class="flex items-center cycle-box">
          <el-input-number
            class="mr-5"
            v-model="deviceNum"
            style="width: 120px"
          />
          <button class="my-button button-blue mr-5" @click="saveDeviceNum">
            保存
          </button>
          <div class="my-pager">
            <el-pagination
              class="mr-5"
              size="large"
              layout="prev, pager, next"
              :total="styleTotal"
              v-model:currentPage="currentStyle"
              @current-change="handleStyleChange"
            />
          </div>
          <button class="my-button button-blue" @click="toggleLock">
            <el-icon v-if="lockMask" class="text-4xl"><Lock /></el-icon
            ><el-icon v-if="!lockMask" class="text-4xl"><Unlock /></el-icon>
          </button>
          <button class="my-button button-green mr-2" @click="configUser">
            用户管理
          </button>
        </div>
      </div>
    </div>
    <!-- 样式一 -->
    <div class="mt-2 style1 status-info" v-if="currentStyle === 1">
      <!-- 设备行列 -->
      <!-- 第一行数据 -->
      <div class="row flex flex-wrap justify-end">
        <div
          class="row-item text-center row-1"
          v-for="(item, index) in rowList1"
          :key="index"
        >
          <!-- 0未启用 1启用 2托管 -->
          <template v-if="item.UseStatus == 1 || item.UseStatus == 3">
            <span v-if="item.Status == 1" class="status-yellow">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 2" class="status-green">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 3" class="status-red">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 4" class="status-orange">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 5" class="status-blue">{{
              item.Number
            }}</span>
            <span v-else class="status-white">{{ item.Number }}</span>
          </template>
          <template v-else-if="item.UseStatus == 2">
            <span v-if="item.Status == 1" class="status-yellow status-charge">{{
              item.Number
            }}</span>
            <span
              v-else-if="item.Status == 2"
              class="status-green status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 3"
              class="status-red status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 4"
              class="status-orange status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 5"
              class="status-blue status-charge"
              >{{ item.Number }}</span
            >
            <span v-else class="status-white status-charge">{{
              item.Number
            }}</span>
          </template>
          <template v-else-if="item.UseStatus == 0">
            <span class="status-hide">{{ item.Number }}</span>
          </template>
          <template v-else>
            <span class="status-white">{{ item.Number }}</span>
          </template>
        </div>
      </div>
      <!-- 第二行数据 -->
      <div class="row flex flex-row-reverse">
        <div
          class="row-item text-center row-2"
          v-for="(item, index) in rowList2"
          :key="index"
        >
          <!-- 0未启用 1启用 2托管 -->
          <template v-if="item.UseStatus == 1 || item.UseStatus == 3">
            <span v-if="item.Status == 1" class="status-yellow">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 2" class="status-green">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 3" class="status-red">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 4" class="status-orange">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 5" class="status-blue">{{
              item.Number
            }}</span>
            <span v-else class="status-white">{{ item.Number }}</span>
          </template>
          <template v-else-if="item.UseStatus == 2">
            <span v-if="item.Status == 1" class="status-yellow status-charge">{{
              item.Number
            }}</span>
            <span
              v-else-if="item.Status == 2"
              class="status-green status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 3"
              class="status-red status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 4"
              class="status-orange status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 5"
              class="status-blue status-charge"
              >{{ item.Number }}</span
            >
            <span v-else class="status-white status-charge">{{
              item.Number
            }}</span>
          </template>
          <template v-else-if="item.UseStatus == 0">
            <span class="status-hide">{{ item.Number }}</span>
          </template>
          <template v-else>
            <span class="status-white">{{ item.Number }}</span>
          </template>
        </div>
      </div>
      <!-- T1 T2 -->
      <div class="row special-list">
        <div
          class="row-item text-center"
          v-for="(item, index) in specialList1"
          :key="index"
        >
          <span v-if="item.Status == 1" class="status-yellow">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 2" class="status-green">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 3" class="status-red">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 4" class="status-orange">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 5" class="status-blue">{{
            item.Number
          }}</span>
          <span v-else class="status-white">{{ item.Number }}</span>
        </div>
      </div>
    </div>
    <!-- 样式二 -->
    <div class="mt-2 style2 status-info" v-if="currentStyle === 2">
      <!-- 设备行列 -->
      <div class="row flex flex-wrap justify-end">
        <div
          class="row-item text-center row-1"
          v-for="(item, index) in rowList12"
          :key="index"
        >
          <!-- 0未启用 1启用 2托管 -->
          <template v-if="item.UseStatus == 1 || item.UseStatus == 3">
            <span v-if="item.Status == 1" class="status-yellow">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 2" class="status-green">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 3" class="status-red">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 4" class="status-orange">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 5" class="status-blue">{{
              item.Number
            }}</span>
            <span v-else class="status-white">{{ item.Number }}</span>
          </template>
          <template v-else-if="item.UseStatus == 2">
            <span v-if="item.Status == 1" class="status-yellow status-charge">{{
              item.Number
            }}</span>
            <span
              v-else-if="item.Status == 2"
              class="status-green status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 3"
              class="status-red status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 4"
              class="status-orange status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 5"
              class="status-blue status-charge"
              >{{ item.Number }}</span
            >
            <span v-else class="status-white status-charge">{{
              item.Number
            }}</span>
          </template>
          <template v-else-if="item.UseStatus == 0">
            <span class="status-hide">{{ item.Number }}</span>
          </template>
          <template v-else>
            <span class="status-white">{{ item.Number }}</span>
          </template>
        </div>
      </div>
      <div class="row flex flex-row-reverse">
        <div
          class="row-item text-center row-2"
          v-for="(item, index) in rowList22"
          :key="index"
        >
          <!-- 0未启用 1启用 2托管 -->
          <template v-if="item.UseStatus == 1 || item.UseStatus == 3">
            <span v-if="item.Status == 1" class="status-yellow">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 2" class="status-green">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 3" class="status-red">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 4" class="status-orange">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 5" class="status-blue">{{
              item.Number
            }}</span>
            <span v-else class="status-white">{{ item.Number }}</span>
          </template>
          <template v-else-if="item.UseStatus == 2">
            <span v-if="item.Status == 1" class="status-yellow status-charge">{{
              item.Number
            }}</span>
            <span
              v-else-if="item.Status == 2"
              class="status-green status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 3"
              class="status-red status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 4"
              class="status-orange status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 5"
              class="status-blue status-charge"
              >{{ item.Number }}</span
            >
            <span v-else class="status-white status-charge">{{
              item.Number
            }}</span>
          </template>
          <template v-else-if="item.UseStatus == 0">
            <span class="status-hide">{{ item.Number }}</span>
          </template>
          <template v-else>
            <span class="status-white">{{ item.Number }}</span>
          </template>
        </div>
      </div>
      <!-- T1 T2 -->
      <div class="row special-list">
        <div
          class="row-item text-center"
          v-for="(item, index) in specialList2"
          :key="index"
        >
          <span v-if="item.Status == 1" class="status-yellow">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 2" class="status-green">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 3" class="status-red">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 4" class="status-orange">{{
            item.Number
          }}</span>
          <span v-else-if="item.Status == 5" class="status-blue">{{
            item.Number
          }}</span>
          <span v-else class="status-white">{{ item.Number }}</span>
        </div>
      </div>
    </div>
    <!-- 样式3 只有一行数据 -->
    <div class="mt-2 status-info" v-if="currentStyle === 3">
      <div class="row flex flex-wrap justify-end">
        <div
          class="row-item text-center row-1"
          v-for="(item, index) in rowList13"
          :key="index"
        >
          <!-- 0未启用 1启用 2托管 -->
          <template v-if="item.UseStatus == 1 || item.UseStatus == 3">
            <span v-if="item.Status == 1" class="status-yellow">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 2" class="status-green">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 3" class="status-red">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 4" class="status-orange">{{
              item.Number
            }}</span>
            <span v-else-if="item.Status == 5" class="status-blue">{{
              item.Number
            }}</span>
            <span v-else class="status-white">{{ item.Number }}</span>
          </template>
          <template v-else-if="item.UseStatus == 2">
            <span v-if="item.Status == 1" class="status-yellow status-charge">{{
              item.Number
            }}</span>
            <span
              v-else-if="item.Status == 2"
              class="status-green status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 3"
              class="status-red status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 4"
              class="status-orange status-charge"
              >{{ item.Number }}</span
            >
            <span
              v-else-if="item.Status == 5"
              class="status-blue status-charge"
              >{{ item.Number }}</span
            >
            <span v-else class="status-white status-charge">{{
              item.Number
            }}</span>
          </template>
          <template v-else-if="item.UseStatus == 0">
            <span class="status-hide">{{ item.Number }}</span>
          </template>
          <template v-else>
            <span class="status-white">{{ item.Number }}</span>
          </template>
        </div>
      </div>
    </div>
  </div>
  <div class="flex justify-between mt-2">
    <!-- 线段信息 -->
    <div class="my-box line-info table-box" style="width: 48%">
      <div class="flex items-center relative">
        <p class="title">
          机种
          <el-select
            class="ml-2"
            v-model="model"
            :disabled="!isEdit"
            placeholder="请选择"
            style="width: 160px"
            @change="getList"
          >
            <el-option
              v-for="item in modelList"
              :key="item.Value"
              :label="item.Label"
              :value="item.Value"
            />
          </el-select>
        </p>
        <div class="flex w-50 line-btn">
          <button
            class="my-button button-blue ml-4"
            :disabled="!isEdit"
            @click="addModel"
          >
            设置
          </button>
          <button
            class="my-button button-red ml-4"
            :disabled="!isEdit"
            @click="getList"
          >
            刷新
          </button>
          <button class="my-button button-green" @click="edit">编辑</button>
          <button class="my-button button-orange" @click="save">保存</button>
        </div>
        <div class="ml-5">
          连接<el-switch
            v-model="connectRun"
            :disabled="connectRun"
            @change="changeConnect"
            class="ml-2"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </div>
        <p>
          <el-select
            class="ml-10"
            v-model="mode"
            :disabled="!isEdit"
            placeholder="请选择"
            style="width: 110px"
          >
            <el-option key="1" label="单机" value="Normal"></el-option>
            <el-option key="2" label="联动" value="Union"></el-option>
          </el-select>
        </p>
        <div class="w-50 absolute" style="right: 10px">
          <el-switch
            v-model="linkRun"
            :disabled="runActive || isEdit || !connectRun"
            @change="changeRun"
            class="ml-2"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </div>
      </div>

      <el-table class="mt-2" :data="lineList" height="570" style="width: 100%">
        <el-table-column
          align="center"
          prop="Index"
          label="序号"
          width="66"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="Name"
          label="名称"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-input v-model="scope.row.Name" :disabled="!isEdit" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="StartNum"
          label="起始编号"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-input v-model="scope.row.StartNum" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="EndNum"
          label="结束编号"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.EndNum"
              @input="colChanged(scope.$index, scope.row.EndNum)"
              @blur="checkEndNum(scope.row, scope.$index)"
              :disabled="!isEdit"
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="Velocity"
          label="线速(s)"
          width="130"
        >
          <template #default="scope">
            <el-input-number
              v-model="scope.row.Velocity"
              :min="3"
              :max="200"
              :disabled="!scope.row.Activity"
              @change="changeVelocity(scope.$index)"
              style="width: 120px"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Activity" label="启用" width="65">
          <template #default="scope">
            <el-switch
              v-model="scope.row.Activity"
              @change="changeActivity(scope.row.Activity, scope.$index)"
              :disabled="!isEdit"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Status" label="运行" width="65">
          <template #default="scope">
            <el-switch
              v-model="scope.row.Status"
              :disabled="
                isEdit ||
                (!linkRun && !scope.row.Activity) ||
                (linkRun && !scope.row.Activity) ||
                (!linkRun && scope.row.Activity)
              "
              @change="changeLineStatus(scope.row, scope.$index)"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="Velocity"
          label="状态"
          width="70"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div>
              <span
                v-if="stateList[scope.$index].State === '0'"
                style="color: #909399"
                >停用</span
              >
              <span
                v-else-if="stateList[scope.$index].State === '2'"
                style="color: green"
                >运行</span
              >
              <span
                v-else-if="stateList[scope.$index].State === '3'"
                style="color: orange"
                >停线</span
              >
              <span v-else style="color: yellow">待机</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格遮罩层 -->
      <div class="line-mask" v-if="lockMask"></div>
    </div>
    <!-- 日志信息 -->
    <div class="my-box log-info table-box" style="width: 33%">
      <p class="my-box-title">日志信息</p>
      <el-table :data="logList" height="570" style="width: 100%">
        <el-table-column
          align="center"
          prop="DateTime"
          label="时间"
          width="240"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="Name"
          label="设备名称"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          prop="Description"
          label="事件信息"
          show-overflow-tooltip
        />
      </el-table>
    </div>
    <!-- 设备状态统计信息 -->
    <div class="my-box" style="width: 18%">
      <p class="my-box-title">设备状态统计</p>
      <div class="flex chart-box mr-2 mt-1 content-center items-center">
        <div ref="chart" class="w-full h-full" :option="chartOptions"></div>
      </div>
    </div>
  </div>
  <!-- 登录 -->
  <Login ref="loginRef" @success="closeLogin" />
  <!-- 机种管理 -->
  <AddModel ref="modelRef" @success="refreshModel" />
  <!-- 用户管理 -->
  <UserConfig ref="userRef" />
</template>
<style lang="less" scoped>
.btn-box {
  :deep(.el-button) {
    font-size: 1.3rem;
    height: 45px;
    padding: 8px 20px;
  }
}

.my-btn {
  background: #cece1d;
  color: #fff;
  border-color: #cece1d;
}
.row-item {
  --num: v-bind(finalNum);
  width: calc((1860px) / var(--num));
  // width: 30.5px;
  span {
    width: 100%;
    display: block;
    height: 40px;
    font-size: 1rem;
    line-height: 40px;
    border: 1px solid #f7f7f7;
  }
}
.special-list {
  position: absolute;
  right: -30px;
  top: 0;
  .row-item {
    width: 30.5px;
  }
}
.style1 {
  .special-list .row-item {
    span {
      height: 80px;
      line-height: 80px;
    }
  }
  .special-list .row-item:nth-child(1) {
    span {
      border-top-right-radius: 10px;
    }
  }
  .special-list .row-item:nth-child(2) {
    span {
      border-bottom-right-radius: 10px;
    }
  }
}
.style2 {
  .special-list .row-item:nth-child(1) {
    span {
      height: 60px;
      line-height: 60px;
      border-top-right-radius: 10px;
    }
  }
  .special-list .row-item:nth-child(2) {
    span {
      height: 40px;
      line-height: 40px;
    }
  }
  .special-list .row-item:nth-child(3) {
    span {
      height: 60px;
      line-height: 60px;
      border-bottom-right-radius: 10px;
    }
  }
}

.table-box,
.cycle-box {
  :deep(.el-table__inner-wrapper) {
    background: #141c36;
  }
  :deep(.el-table) {
    font-size: 1.3rem;
    background-color: #141c36;
  }

  :deep(.el-table__empty-block) {
    background-color: #141c36;
  }

  :deep(.el-table th.el-table__cell) {
    background-color: #143452;
    color: #79a0c9;
    font-weight: 600;
  }

  :deep(.el-table .el-table__cell) {
    background: #141c36;
    color: #799ac1;
    border-bottom: 0;
    padding: 0.3rem 0;
  }

  :deep(
      .el-table--UseStatus-row-hover
        .el-table__body
        tr:hover
        > td.el-table__cell
    ) {
    background-color: #1f4465;
  }

  :deep(.el-input__wrapper) {
    background: #1c324f;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    height: 2.6rem;
    color: #799ac1;
    font-size: 1.3rem;
    text-align: center;
  }

  :deep(.el-input.is-disabled .el-input__wrapper) {
    background: #1c324f;
    box-shadow: none;
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    -webkit-text-fill-color: #799ac1;
  }

  :deep(.el-table) {
    --el-table-border-color: none;
  }

  // 自定义switch
  :deep(.el-switch__core) {
    min-width: 50px;
    height: 25px;
    border-radius: 12px;
  }

  :deep(.el-switch__core .el-switch__action) {
    width: 22px;
    height: 22px;
  }

  :deep(.el-switch.is-checked .el-switch__core .el-switch__action) {
    left: calc(100% - 23px);
  }
  //input-number
  :deep(.el-input-number .el-input__wrapper) {
    padding-left: 20px;
    padding-right: 20px;
  }
  :deep(.el-input-number__decrease) {
    width: 35px;
    background-color: #141c36;
  }
  :deep(.el-input-number__increase) {
    width: 35px;
    background-color: #141c36;
  }
  :deep(.el-table .cell) {
    padding: 0 5px;
  }
  :deep(.el-icon) {
    font-size: 24px;
  }
  :deep(
      .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell
    ) {
    background-color: #2c4a72;
  }
  :deep(.el-table__empty-text) {
    color: #79a0c9;
  }
}
.cycle-box {
  .my-button {
    height: 40px;
    font-size: 18px;
  }
  .button-green {
    width: 90px;
  }
  .button-blue {
    font-size: 18px;
  }
}

.line-info {
  height: 630px;
  font-size: 20px;
  padding-top: 5px;
  .title {
    text-indent: 10px;
  }
  :deep(.el-icon) {
    font-size: 24px;
  }
  :deep(.el-button) {
    width: 70px;
    height: 40px;
  }
  :deep(.el-button > span) {
    font-size: 20px;
  }
}
.error-info {
  :deep(.el-table .el-table__cell) {
    background: #141c36;
    color: #799ac1;
    border-bottom: 0;
  }
}

.log-info {
  height: 630px;
  :deep(.el-table .el-table__cell) {
    background: #141c36;
    color: #799ac1;
    border-bottom: 0;
  }
}

.error-info,
.log-info {
  :deep(.el-table) {
    margin-top: 30px;
    background-color: inherit;
  }

  :deep(.el-table tbody .el-table__cell) {
    height: 53px;
    padding: 0.6rem 0;
  }
}
:deep(.log-info .el-table) {
  margin-top: 3px;
}
.line-info {
  position: relative;
  .line-mask {
    position: absolute;
    top: 0;
    background: var(--el-overlay-color-lighter);
    // background: red;
    width: 100%;
    height: 632px;
    z-index: 99;
  }
}
.my-pager {
  :deep(.el-pager li) {
    width: 40px;
    height: 40px;
    font-size: 20px;
    color: #fff;
    background-color: transparent;
  }
  :deep(.el-pager li.is-active) {
    color: var(--el-pagination-hover-color);
  }
  :deep(button) {
    width: 40px;
    height: 40px;
  }
  :deep(.el-pagination button) {
    background-color: transparent;
  }
  :deep(.btn-next .el-icon) {
    font-size: 20px;
    margin-left: 6px;
    color: #fff;
  }
  :deep(.btn-prev .el-icon) {
    font-size: 20px;
    margin-left: 6px;
    color: #fff;
  }
}
.my-pager + .button-blue {
  width: 45px;
  padding-top: 5px;
}

.chart-box {
  margin-top: 30px;
  height: 530px;
}
.status-info {
  position: relative;
  height: 160px;
  margin-right: 30px;
  .row-2 {
    margin-top: 80px;
  }
}
:deep(.el-table__inner-wrapper::before) {
  display: none;
}
.el-select-dropdown__item {
    font-size: 22px;
}
</style>
